﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml;
using YunZuan.Models.Entities;
using Yunzuan.Foundation.Web;

namespace Yunzuan.Common
{
    public class XMLManage
    {

        public static string xmlPath = HttpContext.Current.Server.MapPath(GlobalConfig.BlackaListURL);


        /// <summary>
        /// 加载xml
        /// </summary>
        public  string LoadXml()
        {
            XmlDocument xmlDoc = new XmlDocument();
            if (File.Exists(xmlPath))
            { 
                xmlDoc.Load(xmlPath);
                {
                    if (HttpContext.Current.Cache.Get("Cache:BlackMobiles") == null)
                    {
                        XmlNode rootM = xmlDoc.SelectSingleNode("List/Mobiles");
                        XmlNodeList list = rootM.ChildNodes;
                        string mobiles = "";
                        foreach (XmlNode r in list)
                        {
                            if (!string.IsNullOrEmpty(r.InnerText))
                            {
                                mobiles += r.InnerText + ",";
                            }
                        }
                        mobiles = mobiles.TrimEnd(',');
                        HttpContext.Current.Cache.Insert("Cache:BlackMobiles", mobiles, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                    }
                }
                {
                    if (HttpContext.Current.Cache.Get("Cache:IPs") == null)
                    {
                        XmlNode rootI = xmlDoc.SelectSingleNode("List/IPs");
                        XmlNodeList list = rootI.ChildNodes;
                        string ips = "";
                        foreach (XmlNode r in list)
                        {
                            if (!string.IsNullOrEmpty(r.InnerText))
                            {
                                ips += r.InnerText + ",";
                            }
                        }
                        ips = ips.TrimEnd(',');
                        HttpContext.Current.Cache.Insert("Cache:BlackIPs", ips, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                    }
                }
            }
            else
            {
                try
                {
                    XmlNode xmlnode = xmlDoc.CreateXmlDeclaration("1.0", "gb2312", null);
                    xmlDoc.AppendChild(xmlnode);
                    XmlElement List = xmlDoc.CreateElement("List"); //添加根结点
                    XmlElement Mobiles = xmlDoc.CreateElement("Mobiles"); //添加手机号节点 
                    XmlElement IPs = xmlDoc.CreateElement("IPs"); //添加IP节点 
                    List.AppendChild(Mobiles);
                    List.AppendChild(IPs);
                    xmlDoc.AppendChild(List);
                    xmlDoc.Save(xmlPath);
                    xmlDoc.Load(xmlPath);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            string xmlMobiles = "";
            HashParam hp = new HashParam();
            XmlNode rootMobiles = xmlDoc.SelectSingleNode("List/Mobiles"); 
            XmlNodeList listMobiles = rootMobiles.ChildNodes;
            foreach (XmlNode r in listMobiles)
            {
                if (!string.IsNullOrEmpty(r.InnerText))
                {
                    xmlMobiles += r.InnerText + ",";
                }
            }
            xmlMobiles = xmlMobiles.TrimEnd(',');
            hp.Add("Mobiles", xmlMobiles);
            string xmlIps = "";
            XmlNode rootIPs = xmlDoc.SelectSingleNode("List/IPs");
            XmlNodeList listIps = rootIPs.ChildNodes;
            foreach (XmlNode r in listIps)
            {
                if (!string.IsNullOrEmpty(r.InnerText))
                {
                    xmlIps += r.InnerText + ",";
                }
            }
            xmlIps = xmlIps.TrimEnd(',');
            hp.Add("IPs", xmlIps);
            return JsonConvert.SerializeObject(hp);
        }

        //添加节点
        public string AddElement(string type,string value)
        {
            XmlDocument xmlDoc = new XmlDocument();
            string xmlFile=LoadXml();
            HashParam hp = JsonConvert.DeserializeObject< HashParam>(xmlFile);
            if (type == "mobile")
            {
                string[] list = hp["Mobiles"].ToString().Split(','); 
                if (list.Contains(value))
                {
                    return JsonConvert.SerializeObject(hp);
                }
                XmlNode MobilesSelect = xmlDoc.SelectSingleNode("List/Mobiles");
                XmlElement Mobile = xmlDoc.CreateElement("Mobile"); //添加手机号节点 
                Mobile.InnerText = value;
                MobilesSelect.AppendChild(Mobile); 
                string mobiles =hp["Mobiles"] +  "," + value;
                mobiles = mobiles.TrimStart(',').TrimEnd(',');
                hp["Mobiles"] = mobiles;
                HttpContext.Current.Cache.Insert("Cache:BlackMobiles" , mobiles, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
            }
            else if (type == "ip")
            {
                string[] list = hp["IPs"].ToString().Split(',');
                if (list.Contains(value))
                    return JsonConvert.SerializeObject(hp);
                XmlNode IPsSelect = xmlDoc.SelectSingleNode("List/IPs");
                XmlElement IP = xmlDoc.CreateElement("IP"); //添加IP节点 
                IP.InnerText = value;
                IPsSelect.AppendChild(IP);
                string ips=hp["IPs"] +"," + value;
                ips = ips.TrimStart(',').TrimEnd(',');
                hp["IPs"] = ips;
                HttpContext.Current.Cache.Insert("Cache:BlackIPs", ips, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
            }
            xmlDoc.Save(xmlPath);
            return JsonConvert.SerializeObject(hp);
        }

        //删出节点
        public string DelElement(string type, string value)
        {
            XmlDocument xmlDoc = new XmlDocument();
            string xmlFile = LoadXml(); 
            HashParam hp = JsonConvert.DeserializeObject<HashParam>(xmlFile);
            if (type == "mobile")
            {
                string[] list = hp["Mobiles"].ToString().Split(',');
                if (!list.Contains(value))
                    return JsonConvert.SerializeObject(hp);
                XmlNode Mobiles = xmlDoc.SelectSingleNode("List/Mobiles");
                foreach (XmlNode xn in Mobiles.ChildNodes)
                {
                    if (xn.InnerText == value)
                    {
                        Mobiles.RemoveChild(xn);
                        hp["Mobiles"] = hp["Mobiles"].ToString().Replace(value, "").Replace(",,","").TrimStart(',').TrimEnd(',');
                        HttpContext.Current.Cache.Insert("Cache:BlackMobiles", hp["Mobiles"].ToString(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                        break;
                    }
                }
            }
            else if (type == "ip")
            {
                string[] list = hp["IPs"].ToString().Split(',');
                if (!list.Contains(value))
                    return JsonConvert.SerializeObject(hp);
                XmlNode IPs = xmlDoc.SelectSingleNode("List/IPs");
                foreach (XmlNode xn in IPs.ChildNodes)
                {
                    if (xn.InnerText == value)
                    {
                        IPs.RemoveChild(xn);
                        hp["IPs"] = hp["IPs"].ToString().Replace(value, "").Replace(",,", "").TrimStart(',').TrimEnd(',');
                        HttpContext.Current.Cache.Insert("Cache:BlackIPs", hp["IPs"].ToString(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                        break;
                    }
                }
            }
            xmlDoc.Save(xmlPath);
            return JsonConvert.SerializeObject(hp);
        } 
    }
}
